var map;
var marker;
var info = [];
var icons = [];
var locations = [] ;
$longitude = 0;
$latitude = 0;
$img = '';
var maerker, i;
var infowindow;
var watchID = false;
var watchCamID;
$ImgLoader = $('<img class="pngload" src="img/loader.png" />');
$fadiv = $('<div class="fadiv"></div>');
$fadin = $('<div class="fadin"></div>');

var urli = encodeURI("http://mobile.broken.fr/cordova/upload.php");

$(document).ready(function(){
	document.addEventListener("deviceready", onDeviceReady, false);
});

//Cordova is ready function
function onDeviceReady() {
	homeSlider();
}
function sM2H() {
	emptyMeDiv('loaders');
	$.mobile.changePage("#home", {
		allowSamePageTransition : true, transition : 'slide', reloadPage : false
		});
}
function sU2H() {
	$.mobile.changePage("#home", {
		allowSamePageTransition : true, reverse : true, transition : 'slide', reloadPage : false
		});
}
function sH2U() {
	$.mobile.changePage("#uploading", {
		allowSamePageTransition : true, transition : 'slide', reloadPage : false
		});
}
function sH2M() {
	$.mobile.changePage("#mapping", {
		allowSamePageTransition : true, reverse : true, transition : 'slide', reloadPage : false
		});
}

function LoadUpload(){
	$('#uploading .loader').append($ImgLoader);
	emptyMeDiv('loaders');
	emptyMeDiv('myImage');
	if(watchID){
		LoadCamera();
	}
	else {
		$('#loaders').html('Chargement de votre position actuelle... ');
		watchCamID = navigator.geolocation.getCurrentPosition(camera_success, geo_error, { maximumAge: 30000, timeout: 30000, enableHighAccuracy: true }); 
	}
}
function LoadCamera(){
	emptyMeDiv('uploading .loader');
	navigator.camera.getPicture(onSuccess, onFail, {
		quality: 50,
		destinationType: Camera.DestinationType.FILE_URI,
		saveToPhotoAlbum : true,
		targetWidth: 720,
		correctOrientation: true
	});
}
function LoadMap() {
	$(window).unbind();
	$(window).bind('pageshow resize orientationchange', function(e){ max_height(); });
	max_height();
	google.load("maps", "3", {"callback": map, other_params: "sensor=true"});
}

function max_height(){
	var h = $('div[data-role="header"]').outerHeight(true);
	var f = $('div[data-role="footer"]').outerHeight(true);
	var w = $(window).height();
	var c = $('div[data-role="content"]');
	var c_h = c.height();
	var c_oh = c.outerHeight(true);
	var c_new = w * 80 / 100;
	var total = h + f + c_oh;
	if(c_h<c.get(0).scrollHeight){
		c.height(c.get(0).scrollHeight);
	}else{
		c.height(c_new);
	}
}

function map(){
	var latlng = new google.maps.LatLng(48.50, 2.20); //Paris centered
	var myOptions = {
		zoom: 5,
		center: latlng,
		streetViewControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		zoomControl: true
	};
	map = new google.maps.Map(document.getElementById("map"), myOptions);

	google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
		geo_success();  
	});
}

//ERROR OR SUCCES
function camera_success(position){
	watchID = true;
	$longitude = position.coords.longitude;
	$latitude = position.coords.latitude;
	LoadCamera();
}
function geo_error(error){
	watchID = false;
	emptyMeDiv('loaders');
	emptyMeDiv('uploading .loader');
	alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
function geo_success(position) {
	setTimeout( function(){ displayMarkers(locations) ; }, 1000);
}
function onSuccess(imageURI) {
	$('#loaders').html('Entrez un commentaire pour votre photo !');
	$divImage = $('#myImage');
	$img = $('<img>');
	$divImage.append($img);
	$img.attr('src', imageURI);
	$imgURL = imageURI;
	$divImage.append('<form id="upSub"><div data-role="fieldcontain"><textarea id="imgCom" rows="3" cols="40"></textarea></div><input type="submit" id="submyth"/></form>');
	$("#upSub").on('submit', function(e) {
		e.preventDefault();
		uploadPhoto($imgURL);
	});
}
function onFail(message) {
	emptyMeDiv('loaders');
	emptyMeDiv('myImage');
	alert('Prise de photo avortée !');
}
function win(r) {
	emptyMeDiv('uploading .loader');
	alert('L\'image a bien été uploadé !');
	emptyMeDiv('loaders');
	emptyMeDiv('myImage');
}
function fail(error) {
	emptyMeDiv('uploading .loader');
	if(error.code == 3){
		alert("Pas de connection internet !");
	}else {
		alert("An error has occurred: Code = " + error.code);
	}
}

//MARKER REF
function displayMarkers(loca){
	for (i = 0; i < loca.length; i++) {
		info[i] =
		('<div class="googlePop"><img class="gmi" src="'+loca[i][3]+'" />' + 
		'<p class="googleImgP"><em>L</em>atitude: ' + loca[i][1] + '<br>' +
		'<em>L</em>ongitude: ' + loca[i][2] + '<br>' + 
		'<em>D</em>ate: ' + loca[i][4] + '</p><br>' +
		'<p><em>C</em>omment: ' + loca[i][0] + '</p>' +
		'</div>' );
		maerker = new google.maps.Marker({
			position: new google.maps.LatLng(loca[i][1], loca[i][2]),
			map: map,
		});
		infowindow = new google.maps.InfoWindow();

		google.maps.event.addListener(maerker, 'click', (function(maerker, i) {
			return function() {
				infowindow.setContent(info[i]);
				infowindow.open(map, maerker);
			}
		})(maerker, i));
	}
}
function drawCircle(m){
	var circle = new google.maps.Circle({
	map: map,
	radius: 100000,
	fillColor: '#AA0000',
	strokeOpacity : 0
	});
	circle.bindTo('center', m, 'position');
}


function uploadPhoto(imageURI) {
	$('#uploading .loader').append($ImgLoader);
	var options = new FileUploadOptions();
	options.fileKey="file";
	options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
	options.mimeType="image/jpeg";

	var params = {
		img : options.fileName,
		longitude : $longitude,
		latitude : $latitude,
		comment : $('#imgCom').val()
	}

	options.params = params;

	var ft = new FileTransfer();
	ft.upload(imageURI, urli, win, fail, options);
}
function homeSlider() {
	//emptyMeDiv('home .homeslider');
	$('#home .loader').append($ImgLoader);
	$.ajax({
		url : "http://mobile.broken.fr/cordova/ajax_fetch_data.php",
		success: successAjaxHome,
		type: "POST",
		data: {
		},
		dataType: "JSON"
	}).done( function() {
		emptyMeDiv('home .loader');        
		$.extend($.event.special.swipe, {
			scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling.
			durationThreshold: 1000, // More time than this, and it isn't a swipe.
			horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
			verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
		});
		$("#home").on('swiperight', sH2M);
		$("#home").on('swipeleft', sH2U);
		$("#mapping").on('swipeleft', sM2H);
		$("#uploading").on('swiperight', sU2H);
		$("#map").on('swipeleft', function(){ return false; });
		$(document).on('pageshow', '#mapping', LoadMap);
		$(document).on('pageshow', '#uploading', LoadUpload);
		//$(document).on('pageshow', '#home', homeSlider);
	});
}

function successAjaxHome(reponse){
	var m = 0;
	for(z in reponse){
		$img = $('<img class="loadImg" data-id="' + m + '">');
		$img.attr('src', 'http://mobile.broken.fr/cordova/uploads/'+reponse[z].image);
		$('.homeslider').append($img);
		locations[m] = [''+reponse[z].comment+'', reponse[z].latitude, reponse[z].longitude, $img.attr('src'), reponse[z].dateAdded];
		m++;
	}

	$('#home .homeslider').on('click', '.loadImg', function(){
		$tid = $(this).data('id');
		$fadin.empty();
		$fadin.append('<img src="' + locations[$tid][3] + '" /><p>' + locations[$tid][0] + '</p>');
		$fadiv.append($fadin);
		$('#home').append($fadiv);
	});
	$('#home').on('click', '.fadiv', function(){
		$(this).remove();
	})
}

//FUNCTION
function emptyMeDiv(div){
	$('#'+div+'').empty();
}